
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>

static char *kbuf[1024];
static int size = 33;
static int align = 8;
static struct kmem_cache *my_cache;

static int __init my_init(void)
{
	int i, j;
	my_cache = kmem_cache_create("testtest-cache", size, align, 0, NULL);
	if (!my_cache) {
		return -ENOMEM;
	}

	pr_info("allocated memory cache success\r\n");

	for (i = 0; i < 1024; i++) {
		kbuf[i] = kmem_cache_alloc(my_cache, GFP_ATOMIC);
		if (!kbuf[i]) {
			pr_err("failed to create a cache object\r\n");
			for (j = 0; j < i; j++) {
				kmem_cache_free(my_cache, kbuf[j]);
			}
			kmem_cache_destroy(my_cache);

			return -1;
		}
		memset(kbuf[i], 0xaa, size);
	}

	pr_info("success get a mem cache object\r\n");

	return 0;
}

static void __exit my_exit(void)
{
	int i;
	for (i = 0; i < 1024; i++)
		kmem_cache_free(my_cache, kbuf[i]);

	pr_info("destroyed a mem cache object\r\n");
	kmem_cache_destroy(my_cache);
}

module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Module named kmemcache.");
